package middleware

import (
	"cgs-server/internal/pkg/code"
	"cgs-server/pkg/log"
	"cgs-server/server"
	"git.mapchang.com/go/base/core"
	"git.mapchang.com/go/errors"
	"github.com/gin-gonic/gin"
	"strings"
)

// ValidateTokenMiddlewareGin gin 认证处理
func ValidateTokenMiddlewareGin(c *gin.Context) {
	r := c.Request

	auth, ok := server.GetApiAuthority(r.URL.Path)
	if !ok {
		// path is not registered.
		log.Errorf("%v is not registered", r.URL.Path)
		core.WriteResponse(c, errors.WithCode(code.ErrPageNotFound, "访问的路径不存在"), nil)
		c.Abort()
		return
	}

	// api needs no authority
	if auth.Auth == string(server.None) {
		logAPI2(r.URL.Path, auth.Auth, "", true)
		c.Next()
		return
	}

	// check whether user has the authority required
	user, _ := server.GetCurrentUser(r)
	username := ""

	// 添加 X-Mode 的请求头判断
	XMode := ""
	isPublic := false
	if len(r.Header) > 0 {
		for k, v := range r.Header {
			if k == "X-Mode" {
				XMode = v[0]
			}
			if k == "Referer" {
				isPublic = strings.Contains(v[0], "public/form")
			}
		}
	}
	if XMode != "" {
		c.Next()
		return
	}
	// 公开表单请求判断
	if isPublic {
		c.Next()
		return
	}

	if user != nil {
		username = user.Username
		for _, item := range user.OperatingAuthorities {
			if item == auth.Auth { // 权限相同
				logAPI2(r.URL.Path, auth.Auth, user.Username, true)
				c.Next()
				return
			}
		}
	}

	// user doesn't has the authority required
	logAPI2(r.URL.Path, auth.Auth, username, false)
	core.WriteResponse(c, errors.WithCode(code.ErrSignatureInvalid, "认证失败"), nil)
	c.Abort()
}

func logAPI2(path string, auth string, username string, success bool) {
	if username == "" {
		// Guest means the user who is not logged in.
		username = "Guest"
	}

	result := "Fail"
	if success {
		result = "Success"
	}
	_ = result

	//log.Infof("%v %v %v %v", path, auth, username, result)
}
